package com.oreilly.ez.web;

import com.oreilly.ez.base.R;
import com.oreilly.ez.entity.WalleCard;
import com.oreilly.ez.repo.WalleCardRepo;
import com.oreilly.ez.repo.WalleItemRepo;
import com.oreilly.ez.repo.WalleTagRepo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Optional;

@RestController
@RequestMapping("/walle-cards")
@Validated
@Slf4j
public class WalleCardCtrl extends BaseCtrl<WalleCard>{

    @Autowired
    private WalleCardRepo walleCardRepo;

    @Autowired
    private WalleItemRepo walleItemRepo;

//    @GetMapping("/tags")
//    public Object tags(){
//
//        return walleTagRepo.findAll();
//    }

    @Override
    public Object find(WalleCard walleCard, Pageable pageable) {

        log.info("walleCard = {}", walleCard);
        Page<WalleCard> walleCardPage = walleCardRepo.findAll(pageable);

        walleCardPage.stream().forEach(card -> {
            Integer sid = card.getSid();

            walleItemRepo.findAllByWalleCard(sid);
        });
        return walleCardPage;
    }

    @Override
    public Object findOne(@PathVariable Integer id){

        Optional<WalleCard> optional = walleCardRepo.findById(id);
        return R.ok(optional);
    }



    @PostMapping
    public Object save(@RequestBody @Valid WalleCard walleCard){



        //新增 新的tag
//        String tags = walleCard.getTags();
//
//        List<WalleTag> dbTags = walleTagRepo.findAll();
//        List<String> dbTagNameList = dbTags.stream().map(tag -> tag.getTagName()).collect(Collectors.toList());

//        String trimTags = StringUtils.trimAllWhitespace(tags);
//        String[] tagArr = trimTags.split(",");
//
//        for (String tag : tagArr) {
//
//            if(!dbTagNameList.contains(tag)){
//                WalleTag walleTag = new WalleTag();
//                walleTag.setTagName(tag);
//                walleTagRepo.save(walleTag);
//            }
//        }

        //save  card
        // 这会自动 保存 rel 关联表

//        List<WalleTag> tagList = walleTagRepo.findAllByTagNameIn(Arrays.asList(tagArr));
//        walleCard.setTagList(tagList);
        walleCardRepo.save(walleCard);

        return R.ok(walleCard);

    }



    @Override
    public Object delete( @PathVariable Integer id ) {

        walleCardRepo.deleteById(id);
        return null;
    }


}
